<?php
/**
 * User: YL
 * Date: 2019/09/12
 */

namespace restful\utils;

use Illuminate\Http\Request;
use restful\cipher\Runtime;

class Cipher
{
    /**
     * @var string
     */
    protected static $module;

    /**
     * 请求
     * @param Request $request
     * @param $params
     * @return string
     */
    public static function request(Request $request, $params)
    {
        if (static::isExec($request)) {
            $config = Env::get(
                sprintf('request.%s', static::$module),
                []
            );
            return Runtime::getInstance($config)->decrypt($params);
        }

        return $params;
    }

    /**
     * 响应
     * @param Request $request
     * @param array $data
     * @return array|string
     */
    public static function response(Request $request, array $data)
    {

        if (static::isExec($request)) {
            $config = Env::get(
                sprintf('request.%s', static::$module),
                []
            );
            return Runtime::getInstance($config)->encrypt(json_encode($data));
        }

        return $data;
    }

    /**
     * 是否运行
     * @param Request $request
     * @return bool
     */
    protected static function isExec(Request $request)
    {
        $controller = Dispatch::getInstance($request)->getController();
        $method = Dispatch::getInstance($request)->getMethod();
        static::$module = Dispatch::getInstance($request)->getModule();

        $isDebug = Env::get(
            sprintf('request.%s_debug', strtoupper(static::$module)),
            false
        );
        $methods = Dispatch::run($controller, 'getNoNeedCipherMethod');

        return ! $isDebug && ! in_array($method, $methods);
    }
}
